<template>
  <div class="Hcont" v-if="homepage === 5">
    <!-- 头部导航 -->
    <div class="Hhead" @click="toHcont">
      <div class="hd1">
        <img src="../assets/logo3.png" alt="系统logo" class="hd11">
        <div class="hd12 noselect">
          <div class="hd121">智能配送</div>
          <div class="hd122">Intelligent Distribution</div>
        </div>
      </div>
      <img src="../assets/work.png" alt="工作图标" class="hd2">
      <div class="hd4"></div>
      <div class="hd3">
        <img src="../assets/tou.png" alt="用户头像" class="hd31">
        <el-dropdown>
          <span class="el-dropdown-link noselect xiaoshou" @click.stop>
            Qin<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :icon="Postcard">个人信息</el-dropdown-item>
              <el-dropdown-item :icon="User" @click="customer">AI客服</el-dropdown-item>
              <el-dropdown-item :icon="Setting">设置</el-dropdown-item>
              <el-dropdown-item :icon="Switch">切换账号</el-dropdown-item>
              <el-dropdown-item :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="hb"></div>

    <!-- 主体内容 -->
    <div class="Hbody">
      <!-- 侧边导航 -->
      <div class="bdl">
        <div class="bdl1">
          <div class="bdl11 noselect xiaoshou" :class="{ 'active-nav': homepage === 2 }" @click="uav">
            <img src="../assets/UAV.png" alt="无人机图标" class="bdl111">
            <div class="bdl112">无人机管理</div>
          </div>
          <div class="bdl12 noselect xiaoshou" :class="{ 'active-nav': homepage === 3 }" @click="mm">
            <img src="../assets/MM.png" alt="商户图标" class="bdl121">
            <div class="bdl122">商户管理</div>
          </div>
          <div class="bdl13 noselect xiaoshou" :class="{ 'active-nav': homepage === 4 }" @click="task">
            <img src="../assets/task.png" alt="任务图标" class="bdl131">
            <div class="bdl132">任务管理</div>
          </div>
          <div class="bdl14 noselect xiaoshou active-nav" @click="map">
            <img src="../assets/map.png" alt="地图图标" class="bdl141">
            <div class="bdl142">地图与空域管理</div>
          </div>
          <div class="bdl15 noselect xiaoshou" :class="{ 'active-nav': homepage === 6 }" @click="alarm">
            <img src="../assets/alarm.png" alt="告警图标" class="bdl151">
            <div class="bdl152">告警中心</div>
          </div>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="bdr">
        <!-- 顶部工具栏 -->
        <div class="map-toolbar mb-4 flex justify-between items-center">
          <div class="flex space-x-4">
            <el-button type="primary" @click="addAirspace">添加空域</el-button>
            <el-button type="success" @click="refreshMap">刷新地图</el-button>
            <el-button type="info" @click="exportMap">导出地图</el-button>
          </div>
          <div class="flex space-x-4">
            <el-input v-model="searchKeyword" placeholder="搜索位置..." class="w-64" @keyup.enter="searchLocation">
               <template #append>
                <el-button  @click="searchLocation">搜索</el-button>
                </template>
            </el-input>
            <el-select v-model="mapType" placeholder="地图类型" class="w-40">
              <el-option label="标准地图" value="standard"></el-option>
              <el-option label="卫星地图" value="satellite"></el-option>
              <el-option label="混合地图" value="hybrid"></el-option>
            </el-select>
          </div>
        </div>

        <!-- 地图容器 -->
        <div class="map-container flex-1 rounded-lg overflow-hidden shadow-lg border border-gray-200 relative">
          <!-- 地图组件 -->
          <div id="map" class="w-full h-full"></div>

          <!-- 地图图层控制 -->
          <div class="absolute top-4 right-4 bg-white p-3 rounded-lg shadow-lg z-10">
            <div class="font-medium mb-2">图层控制</div>
            <el-checkbox-group v-model="activeLayers">
              <el-checkbox label="uavRoutes">无人机航线</el-checkbox>
              <el-checkbox label="airspaces">限制空域</el-checkbox>
              <el-checkbox label="merchants">商户位置</el-checkbox>
              <el-checkbox label="deliveryPoints">配送点</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>

        <!-- 空域管理表格 -->
        <div class="airspace-table mt-4">
          <el-card shadow="hover">
            <div class="flex justify-between items-center mb-4">
              <h3 class="text-lg font-semibold">空域信息列表</h3>
              <div class="flex space-x-2">
                <el-button size="small" type="primary" @click="batchDelete">批量删除</el-button>
                <el-button size="small" type="success" @click="refreshAirspaceTable">刷新</el-button>
              </div>
            </div>
            <el-table
              :data="airspaceList"
              border
              stripe
              size="small"
              height="300"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="id" label="ID" width="80"></el-table-column>
              <el-table-column prop="name" label="空域名称" width="150"></el-table-column>
              <el-table-column prop="type" label="空域类型" width="120">
                <template #default="scope">
                  <el-tag :type="getAirspaceTypeTag(scope.row.type)">{{ scope.row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="altitude" label="高度限制(m)" width="120"></el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
    {{ scope.row.name }}
  </template>
              </el-table-column>
              <el-table-column prop="creator" label="创建人" width="100"></el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="primary" @click="editAirspace(scope.row)">编辑</el-button>
                  <el-button size="mini" type="danger" @click="deleteAirspace(scope.row.id)">删除</el-button>
                  <el-button size="mini" type="info" @click="viewAirspace(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页控件 -->
            <div class="flex justify-between items-center mt-4">
              <div class="text-sm text-gray-500">
                共 {{ totalAirspaces }} 条记录
              </div>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalAirspaces">
              </el-pagination>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>

  <!-- 添加/编辑空域对话框 -->
  <el-dialog v-model="airspaceDialogVisible" title="空域信息" width="60%">
    <template #content>
      <el-form :model="airspaceForm" :rules="airspaceFormRules" ref="airspaceFormRef" label-width="120px">
        <el-form-item label="空域名称" prop="name">
          <el-input v-model="airspaceForm.name"></el-input>
        </el-form-item>
        <el-form-item label="空域类型" prop="type">
          <el-radio-group v-model="airspaceForm.type">
            <el-radio label="禁飞区">禁飞区</el-radio>
            <el-radio label="限飞区">限飞区</el-radio>
            <el-radio label="管控区">管控区</el-radio>
            <el-radio label="适飞区">适飞区</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="高度限制(m)" prop="altitude">
          <el-input-number v-model="airspaceForm.altitude" :min="0" :max="500" :step="10"></el-input-number>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input type="textarea" v-model="airspaceForm.description" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="空域状态" prop="status">
          <el-radio-group v-model="airspaceForm.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="边界点坐标" prop="coordinates">
          <el-input type="textarea" v-model="airspaceForm.coordinates" :rows="6" placeholder="请输入边界点坐标，格式：经度,纬度;经度,纬度;..."></el-input>
          <div class="mt-2">
            <el-button size="small" type="primary" @click="drawAirspaceOnMap">在地图上绘制</el-button>
            <el-button size="small" type="info" @click="importCoordinates">导入坐标</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="airspaceDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveAirspace">保存</el-button>
    </template>
  </el-dialog>

  <!-- 查看空域对话框 -->
  <el-dialog v-model="viewAirspaceDialogVisible" title="空域详情" width="60%">
    <template #content>
      <el-card class="mb-3">
        <div class="flex items-center mb-3">
          <span class="font-medium mr-2">空域名称：</span>
          <span>{{ viewAirspaceData.name }}</span>
        </div>
        <div class="flex items-center mb-3">
          <span class="font-medium mr-2">空域类型：</span>
          <el-tag :type="getAirspaceTypeTag(viewAirspaceData.type)">{{ viewAirspaceData.type }}</el-tag>
        </div>
        <div class="flex items-center mb-3">
          <span class="font-medium mr-2">高度限制：</span>
          <span>{{ viewAirspaceData.altitude }} 米</span>
        </div>
        <div class="flex items-center mb-3">
          <span class="font-medium mr-2">状态：</span>
          <el-tag :type="getAirspaceStatusTag(viewAirspaceData.status)">{{ viewAirspaceData.status }}</el-tag>
        </div>
        <div class="flex items-start mb-3">
          <span class="font-medium mr-2">描述信息：</span>
          <span>{{ viewAirspaceData.description }}</span>
        </div>
        <div class="flex items-start">
          <span class="font-medium mr-2">边界点坐标：</span>
          <div class="w-full bg-gray-50 p-2 rounded border border-gray-200 max-h-40 overflow-y-auto">
            {{ viewAirspaceData.coordinates }}
          </div>
        </div>
      </el-card>
      <div class="map-preview rounded-lg overflow-hidden shadow border border-gray-200 h-80">
        <!-- 这里是地图预览区域 -->
        <div id="airspaceMapPreview" class="w-full h-full"></div>
      </div>
    </template>
    <template #footer>
      <el-button @click="viewAirspaceDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'
import { 
  ArrowDown, Postcard, User, Setting, Switch, SwitchButton
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const router = useRouter()

// 页面状态管理
const homepage = ref(5) // 当前为地图与空域管理页面
// 导航方法
const toHcont = () => {
  homepage.value = 1
  router.push('/HomeViews')
}
const uav = () => { 
  homepage.value = 2
  router.push('/navViews') 
}
const mm = () => { 
  homepage.value = 3
  router.push('/mmViews') 
}
const task = () => { 
  homepage.value = 4 
  router.push('/taskViews')
}
const map = () => { 
  homepage.value = 5
  router.push('/mapViews')
}
const alarm = () => { 
  homepage.value = 6
  router.push('/alarmViews') 
}
const customer = () => { 
  router.push("/chatViews") 
}

// 地图相关数据
const mapType = ref('standard')
const searchKeyword = ref('')
const activeLayers = ref(['uavRoutes', 'airspaces', 'merchants', 'deliveryPoints'])

// 空域管理相关数据
const airspaceList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalAirspaces = ref(0)
const multipleSelection = ref([])

// 空域表单相关
const airspaceDialogVisible = ref(false)
const airspaceForm = ref({
  id: null,
  name: '',
  type: '禁飞区',
  altitude: 120,
  description: '',
  status: '启用',
  coordinates: ''
})
const airspaceFormRef = ref(null)
const airspaceFormRules = ref({
  name: [
    { required: true, message: '请输入空域名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择空域类型', trigger: 'change' }
  ],
  altitude: [
    { required: true, message: '请输入高度限制', trigger: 'blur' },
    { type: 'number', message: '高度限制必须为数字值', trigger: 'blur' }
  ],
  coordinates: [
    { required: true, message: '请输入边界点坐标', trigger: 'blur' }
  ]
})

// 查看空域对话框
const viewAirspaceDialogVisible = ref(false)
const viewAirspaceData = ref({})

// 模拟数据 - 实际项目中应从后端获取
const mockAirspaceList = [
  { id: 1, name: '城市中心禁飞区', type: '禁飞区', altitude: 100, status: '启用', creator: '系统管理员', createTime: '2025-06-15 10:30:00', coordinates: '116.397128,39.916527;116.397457,39.915470;116.398422,39.915669;116.398109,39.916722' },
  { id: 2, name: '机场限飞区', type: '限飞区', altitude: 300, status: '启用', creator: '机场管理处', createTime: '2025-06-18 14:20:00', coordinates: '116.387128,39.926527;116.387457,39.925470;116.388422,39.925669;116.388109,39.926722;116.389109,39.926722' },
  { id: 3, name: '商业区适飞区', type: '适飞区', altitude: 80, status: '启用', creator: '规划部门', createTime: '2025-06-20 09:15:00', coordinates: '116.407128,39.906527;116.407457,39.905470;116.408422,39.905669;116.408109,39.906722' }
]

// 生命周期钩子
onMounted(() => {
  // 初始化地图
  initMap()
  
  // 获取空域列表
  getAirspaceList()
})

// 初始化地图
const initMap = () => {
  console.log('地图初始化完成')
  setTimeout(() => {
    loadMapLayers()
  }, 1000)
}

// 加载地图图层
const loadMapLayers = () => {
  console.log('加载地图图层:', activeLayers.value)
}

// 获取空域列表
const getAirspaceList = () => {
  // 模拟从后端获取数据
  setTimeout(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    airspaceList.value = mockAirspaceList.slice(start, end)
    totalAirspaces.value = mockAirspaceList.length
  }, 300)
}

// 表格选择变化处理
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 分页相关方法
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  getAirspaceList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  getAirspaceList()
}

// 刷新地图
const refreshMap = () => {
  ElMessage.info('地图刷新中...')
  initMap()
}

// 导出地图
const exportMap = () => {
  ElMessage.success('地图导出成功')
}

// 搜索位置
const searchLocation = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  ElMessage.info(`搜索位置: ${searchKeyword.value}`)
}

// 添加空域
const addAirspace = () => {
  airspaceForm.value = {
    id: null,
    name: '',
    type: '禁飞区',
    altitude: 120,
    description: '',
    status: '启用',
    coordinates: ''
  }
  airspaceDialogVisible.value = true
}

// 编辑空域
const editAirspace = (row) => {
  airspaceForm.value = { ...row }
  airspaceDialogVisible.value = true
}

// 删除空域
const deleteAirspace = (id) => {
  ElMessageBox.confirm(
    '确定要删除该空域信息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = mockAirspaceList.findIndex(item => item.id === id)
    if (index !== -1) {
      mockAirspaceList.splice(index, 1)
      getAirspaceList()
      ElMessage.success('删除成功')
    }
  })
}

// 批量删除
const batchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要删除的空域')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${multipleSelection.value.length} 个空域信息吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const ids = multipleSelection.value.map(item => item.id)
    for (let i = mockAirspaceList.length - 1; i >= 0; i--) {
      if (ids.includes(mockAirspaceList[i].id)) {
        mockAirspaceList.splice(i, 1)
      }
    }
    multipleSelection.value = []
    getAirspaceList()
    ElMessage.success('批量删除成功')
  })
}

// 查看空域
const viewAirspace = (row) => {
  viewAirspaceData.value = { ...row }
  viewAirspaceDialogVisible.value = true
  
  // 初始化查看对话框中的地图
  setTimeout(() => {
    initAirspacePreviewMap()
  }, 300)
}

// 初始化空域预览地图
const initAirspacePreviewMap = () => {
  console.log('初始化空域预览地图')
}

// 保存空域
const saveAirspace = () => {
  if (airspaceForm.value.id) {
    // 更新操作
    const index = mockAirspaceList.findIndex(item => item.id === airspaceForm.value.id)
    if (index !== -1) {
      mockAirspaceList[index] = { ...airspaceForm.value }
    }
  } else {
    // 新增操作
    const newId = Math.max(...mockAirspaceList.map(item => item.id)) + 1
    airspaceForm.value.id = newId
    airspaceForm.value.createTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
    airspaceForm.value.creator = '系统管理员'
    mockAirspaceList.push({ ...airspaceForm.value })
  }
  
  airspaceDialogVisible.value = false
  getAirspaceList()
  ElMessage.success('保存成功')
}

// 刷新空域表格
const refreshAirspaceTable = () => {
  getAirspaceList()
  ElMessage.info('数据刷新成功')
}

// 在地图上绘制空域
const drawAirspaceOnMap = () => {
  ElMessage.info('请在地图上绘制空域边界')
}

// 导入坐标
const importCoordinates = () => {
  ElMessage.info('坐标导入功能开发中')
}

// 获取空域类型标签样式
const getAirspaceTypeTag = (type) => {
  const map = {
    '禁飞区': 'danger',
    '限飞区': 'warning',
    '管控区': 'info',
    '适飞区': 'success'
  }
  return map[type] || 'default'
}

// 获取空域状态标签样式
const getAirspaceStatusTag = (status) => {
  const map = {
    '启用': 'success',
    '禁用': 'danger'
  }
  return map[status] || 'default'
}
</script>

<style scoped>
/* 保持原有样式不变 */
.Hcont{
    border-radius: 20px;
    display: flex;
    flex-direction: column;
    width: 97vw;
    height: 98vh;
    overflow: hidden;
    background-color: rgb(239, 239, 238);
}
.Hhead{
  height: 100px;
  width: 100%;
  background-color: rgb(86, 119, 231);
  display: flex;
  flex: none;
  align-items: center;
}
.hd1{
  display: flex;
  margin-left: 60px;
}
.hd11{
  width: 60px;
  border-radius: 100%;
  margin-right: 20px;
}
.hd12{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.hd121{
  font-size: 24px;
  font-weight: 500;
  letter-spacing: 3px;
  color: white;
}
.hd122{
  font-size: 12px;
  color: white;
}
.hd2{
  margin-left: 100px;
  width: 70px;
  margin-top: 30px;
}
.hd3{
  margin-right: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.hd31{
  width: 50px;
  border-radius: 100%;
  margin-right: 10px;
}
.el-dropdown-link{
  color: white;
   outline: none;
}
.hd4{
  flex: 1;
}
.hb{
  width: 100%;
  height: 1px;
  flex: none;
}
.Hbody{
   display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}
.bdl{
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 280px;
  background-color: rgb(30, 58, 138);
}
.bdl1{
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: center;
  margin-top: 50px;
}
.bdl11,.bdl12,.bdl13,.bdl14,.bdl15{
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
.bdl11:hover,.bdl12:hover,.bdl13:hover,.bdl14:hover,.bdl15:hover{
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px); 
  background-color: rgb(156, 188, 249);
  border-radius: 10px;
}
.bdl11:active,.bdl12:active,.bdl13:active,.bdl14:active,.bdl15:active{
  transform: scale(0.97);
  box-shadow: 0 4px 6px -1px rgba(93, 102, 122, 0.1);
}
.bdl111,.bdl121,.bdl131,.bdl141,.bdl151{
  width: 20px;
  padding-right: 10px;
}
.bdl112,.bdl122,.bdl132,.bdl142,.bdl152{
  font-size: 24px;
  font-weight: 400;
  color: white;
}

.active-nav {
  background-color: rgb(156, 188, 249);
  border-radius: 10px;
}

.bdr {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.map-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.map-container {
  flex: 1;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #ebedf0;
  position: relative;
}

.airspace-table {
  margin-top: 16px;
}

.noselect {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
</style>